package com.citic.netty.server.handler;

import java.util.ArrayList;
import java.util.List;

import com.citic.netty.common.protocol.request.CreateGroupRequestPacket;
import com.citic.netty.common.protocol.response.CreateGroupResponsePacket;
import com.citic.netty.common.utils.IDUtil;
import com.citic.netty.common.utils.SessionUtil;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

@ChannelHandler.Sharable
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket>{

    public static final CreateGroupRequestHandler INSTANCE = new CreateGroupRequestHandler();

    private CreateGroupRequestHandler() {

    }
    
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) throws Exception {
		List<String> userIds = createGroupRequestPacket.getUserIdList();
        List<String> usernames = new ArrayList<>();		
        
        // 1. 创建一个 channel 分组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        
        // 2. 筛选出待加入群聊的用户的 channel 和 userName
        for (String userId : userIds) {
            Channel channel = SessionUtil.getChannel(userId);
            if (channel != null) {
                channelGroup.add(channel);
                usernames.add(SessionUtil.getSession(channel).getUsername());
            }
        }
        
        // 3. 创建群聊创建结果的响应
        String groupId = IDUtil.randomId();
        CreateGroupResponsePacket createGroupResponsePacket = new CreateGroupResponsePacket();
        createGroupResponsePacket.setSuccess(true);
        createGroupResponsePacket.setGroupId(groupId);
        createGroupResponsePacket.setUsernames(usernames);
        
        // 4. 给每个客户端发送拉群通知
        channelGroup.writeAndFlush(createGroupResponsePacket);
        
        System.out.print("群创建成功，id 为[" + createGroupResponsePacket.getGroupId() + "], ");
        System.out.println("群里面有：" + createGroupResponsePacket.getUsernames());
        
        // 5. 保存群组相关的信息
        SessionUtil.bindChannelGroup(groupId, channelGroup);
	}

}
